const TOKEN_KEY = 'token';
const MENU_STORAGE = 'menuStorage'
const ROLES_STORAGE = 'rolrsStorage'
const isLogin = () => {
  return !!localStorage.getItem(TOKEN_KEY);
};

const getToken = () => {
  return localStorage.getItem(TOKEN_KEY);
};

const setToken = (token: string) => {
  localStorage.setItem(TOKEN_KEY, token);
};

const clearToken = () => {
  localStorage.removeItem(TOKEN_KEY);
};


const getMenuStorage = () => {
  return localStorage.getItem(MENU_STORAGE);
};

const setMenuStorage = (menuStorage: string) => {
  localStorage.setItem(MENU_STORAGE, menuStorage);
};

const clearMenuStorage = () => {
  localStorage.removeItem(MENU_STORAGE);
};


const getRolesStorage = () => {
  let rolesStorage: any = localStorage.getItem(ROLES_STORAGE)
  if (isValidJSON(rolesStorage)) {
    return (JSON.parse(rolesStorage) || [])
  }
  return []
};

const setRolesStorage = (rolesStorage: string) => {
  localStorage.setItem(ROLES_STORAGE, rolesStorage);
};

const clearRolesStorage = () => {
  localStorage.removeItem(ROLES_STORAGE);
};


const isNonEmptyString = (value: any) => {
  return typeof value === 'string' && value.length > 0;
}

const getMenuName = (value: string) => {
  const list = value?.split('/')
  if (list?.length < 1) return value || ''
  return list[list?.length - 1]
}
const getRouterName = (value: string) => {
  const list = value?.split('/')
  if (list?.length !== 3) return null
  return {
    key: list[1],
    value: list[2]
  }
}

const isValidJSON = (str: any) => {
  try {
    JSON.parse(str);
    return true; // 字符串是有效的 JSON
  } catch (e) {
    return false; // 字符串不是有效的 JSON
  }
}

const getTime = (timestamp: number) => {
  if (!timestamp) return ''
  if (String(timestamp).length === 10) {
    timestamp = timestamp * 1000
  }
  // 创建日期对象
  let date = new Date(timestamp);
  // 格式化输出
  let formattedDate = date.toLocaleString(); // 默认格式
  return formattedDate
}

const ishavePermission = (id: number, roles: any) => {
  if (id && roles?.length > 0) {
    return roles?.some((item: any) => item.id === id)
  }
  return false
}

export {
  isLogin,
  getToken,
  setToken,
  clearToken,
  isNonEmptyString,
  getMenuName,
  getRouterName,
  getMenuStorage,
  setMenuStorage,
  clearMenuStorage,
  isValidJSON,
  getTime,
  ishavePermission,
  getRolesStorage,
  setRolesStorage,
  clearRolesStorage,
};
